//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "PurchaseDlg.h"
#include "FormUtilities.h"
#include "Calendar.h"
#include "FirmSearchDlg.h"
#include "Error.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"

const int NO_SUCH_FIRM  = 1;
const int NO_SUCH_MODEL = 2;

//---------------------------------------------------------------------------

__fastcall TfrmPurchaseDlg::TfrmPurchaseDlg(TComponent* Owner, TDatabase * dbMain)
        : TForm(Owner)
{
   TFormUtilities::LocateForm(( TForm*)Owner, this);

   this->dbMain = dbMain;
   bridge = new TGlassesBridge(dbMain);
   selectedFirm  = new TGlassesFirm();
   selectedModel  = new TGlassesModel();
   this->Caption = "Add new purchase";
}


//---------------------------------------------------------------------------
void __fastcall TfrmPurchaseDlg::btnDateClick(TObject *Sender)
{
/*
   TfrmCalendar * frmCalendar;

   frmCalendar = new TfrmCalendar( this);

   try
   {
      if ( edtDate->Text.Length() > 0)
         frmCalendar->calendar->Date = StrToDate( edtDate->Text);

      if ( frmCalendar->ShowModal() == mrOk)
         edtDate->Text = DateToStr( frmCalendar->calendar->Date);
   }
   __finally
   {
      delete frmCalendar;
   }
   */
}
//---------------------------------------------------------------------------


void __fastcall TfrmPurchaseDlg::btnFirmClick(TObject *Sender)
{
   TfrmFirmSearchDlg* frmSearchDlg = new TfrmFirmSearchDlg(this, dbMain, bridge, selectedFirm);

   try
   {
      if(frmSearchDlg->ShowModal() == mrOk)
      {
         edtFirm->Text = selectedFirm->name;   
      }
   }
   __finally
   {
      delete frmSearchDlg;
   }
}
//---------------------------------------------------------------------------

void __fastcall TfrmPurchaseDlg::FormDestroy(TObject *Sender)
{
   delete selectedFirm;
   delete bridge;
}
//---------------------------------------------------------------------------


void TfrmPurchaseDlg::SelectFirmIfNeeded()
{
   if (selectedFirm->id == -1)
   {
      if(!bridge->GetFirm(edtFirm->Text, selectedFirm))
      {
         throw new TError(NO_SUCH_FIRM, "No such firm");
      }
   }
}

void TfrmPurchaseDlg::SelectModelIfNeeded()
{
   if (selectedModel->firmID == -1)
   {
      if(!bridge->GetModel(selectedFirm->id, edtModel->Text, selectedModel))
      {
         throw new TError(NO_SUCH_MODEL, "No such model");
      }
   }
}

void __fastcall TfrmPurchaseDlg::btnOkClick(TObject *Sender)
{
   SelectFirmIfNeeded();
   SelectModelIfNeeded();
}
//---------------------------------------------------------------------------

